package com.abigdreamer.im.client.module.network.socket;

import java.net.InetSocketAddress;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import com.abigdreamer.im.client.module.network.handler.ClientFileHandler;
import com.abigdreamer.im.client.util.EIMLogger;

/**
 */
public class ClientFileSocket extends EIMClientSocket {

	private static ClientFileSocket instance;

	public static ClientFileSocket getInstance() {
		if (instance == null) {
			instance = new ClientFileSocket();
		}
		return instance;
	}

	private ClientFileSocket() {
		this.initSocket();
	}

	public boolean closedSocket() {
		try {
			this.getConnector().dispose();
			this.setStart(false);
			EIMLogger.INFO("客户关闭了与服务器的文件消息的连接");
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public void initSocket() {
		this.setHandlerAdapter(new ClientFileHandler());
		this.setConnector(new NioSocketConnector());
		this.setServer_IP_Port(SocketConfig.serverIP);
		this.setServer_Socket_Port(SocketConfig.serverFilePort);
		EIMLogger.INFO("客户初始化了与服务器的连接");
	}

	public boolean startSocket() {
		try {
			if (this.isStart() == false) {
				DefaultIoFilterChainBuilder chain = this.getConnector().getFilterChain();
				ObjectSerializationCodecFactory objscf = new ObjectSerializationCodecFactory();
				ProtocolCodecFilter protocolCodecFilter = new ProtocolCodecFilter(objscf);
				chain.addLast("myFileChain", protocolCodecFilter);
				this.getConnector().setHandler(this.getHandlerAdapter());
				/** 设置连接超时的时间 为：一分钟 这个超时不可以过小 */
				this.getConnector().setConnectTimeoutMillis(EIMClientSocket.timeOutMillis);
				EIMLogger.INFO("ip/port:" + this.getServer_IP_Port() + "/" + this.getServer_Socket_Port());
				InetSocketAddress fileInetSocketAddress = new InetSocketAddress(this.getServer_IP_Port(), this.getServer_Socket_Port());
				/** 建立连接 */
				this.connectFuture = this.getConnector().connect(fileInetSocketAddress);
				EIMLogger.INFO("已经建立用户的文件连接");
				this.setStart(true);
				EIMLogger.INFO("客户开启了与文件服务器的连接");
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

}
